<?php
declare(strict_types=1);

namespace Service\MemberService;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\MemberBank;
use App\Model\BbcModel\Bank;
use Service\MessageService\SmsService;

/**
 * TO C/B SBBC用户银行卡管理
 * @author hj
 */
class MemberBankService extends BaseService 
{
    /**
     * 绑定的银行卡列表
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function bankList(array $param)
    {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        $result = MemberBank::where('mid', (int)($param['mid']))->where('df', 0)->select(['id', 'bankcard', 'bank_name', 'card_type'])->get();
        if ($result->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功', ['list' => []]);
        }
        $result->each(function ($item, $key) {
            $item->bankcard = "**** **** **** " . substr($item->bankcard, -4);;
            $item->type = MemberBank::$type[$item->card_type] ?? '';
            return $item;
        });
        return Normal::returnCode(Normal::SUC, '获取成功', ['list' => $result->toArray()]);
    }

    /**
     * 新增银行卡
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function addBank(array $param)
    {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        $validateRes = self::addArgumentValidate($param);
        if ($validateRes['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $validateRes['msg'] ?? 'invalid argument');
        }
        if (!isDebugMode()) {
            $result = SmsService::instance()->checkSmsCode($param['cid'], $param['mobile'], $param['code']);
            if ($result['code'] != Normal::SUC) {
                return $result;
            }
        }
        $addData = [
            'true_name' => $param['true_name'],
            'bankcard'  => str_replace(array("\r\n", "\r", "\n"), "", trim($param['bankcard'])),
            'mobile'    => $param['mobile'],
            'card_type' => $param['card_type'],
            'sid'       => getSID(),
            'bank_name' => Bank::where('id', (int)($param['bank_id']))->value('name'),
            'bank_id'   => $param['bank_id'],
            'mid'       => $param['mid'],
        ];
        if ($param['card_type'] == 1) {
            $addData['idcard'] = $param['idcard'];
        }
        if ($param['card_type'] == 2) {
            $addData['org_code'] = $param['org_code'];
            $addData['org_name'] = $param['org_name'];
        }
        $result = MemberBank::insert($addData);
        if (!$result) {
            return Normal::returnCode(Normal::FAIL, '添加失败');
        }
        return Normal::returnCode(Normal::SUC, '添加成功');

    }

    /**
     * 编辑银行卡
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function editBank(array $param)
    {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        if (!isset($param['id']) || empty($param['id']) || (preg_match("/^[1-9]\d*$/", (string)$param['id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument id');
        }
        $validateRes = self::addArgumentValidate($param);
        if ($validateRes['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $validateRes['msg'] ?? 'invalid argument');
        }
        $info = MemberBank::where('id', (int)($param['id']))->first();
        if (!$info) {
            return Normal::returnCode(Normal::FAIL, '银行卡不存在');
        }
        $info->true_name = $param['true_name'];
        $info->bankcard  = str_replace(array("\r\n", "\r", "\n"), "", trim($param['bankcard']));
        $info->mobile    = $param['mobile'];
        $info->card_type = $param['card_type'];
        $info->sid       = getSID();
        $info->bank_name = Bank::where('id', (int)($param['bank_id']))->value('name');
        $info->bank_id   = $param['bank_id'];
        $info->mid       = $param['mid'];
        if ($param['card_type'] == 1) {
            $info->idcard = $param['idcard'];
        }
        if ($param['card_type'] == 2) {
            $info->org_code = $param['org_code'];
            $info->org_name = $param['org_name'];
        }
        $result = $info->save();
        if (!$result) {
            return Normal::returnCode(Normal::FAIL, '修改失败');
        }
        return Normal::returnCode(Normal::SUC, '修改成功');
    }

    /**
     * 银行卡详情
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function detail(array $param)
    {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        if (!isset($param['id']) || empty($param['id']) || (preg_match("/^[1-9]\d*$/", (string)$param['id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument id');
        }
        $info = MemberBank::where('id', (int)($param['id']))->where('mid', (int)($param['mid']))->first();
        if (!$info) {
            return Normal::returnCode(Normal::FAIL, '银行卡信息不存在');
        }
        return Normal::returnCode(Normal::SUC, '获取成功', $info->toArray());
    }

    /**
     * 删除银行卡
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function delBank(array $param)
    {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        if (!isset($param['id']) || empty($param['id']) || (preg_match("/^[1-9]\d*$/", (string)$param['id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument id');
        }
        $info = MemberBank::where('id', (int)($param['id']))->where('mid', (int)($param['mid']))->first();
        if (!$info) {
            return Normal::returnCode(Normal::FAIL, '银行卡信息不存在');
        }
        $result = $info->delete();
        if (!$result) {
            return Normal::returnCode(Normal::FAIL, '删除失败');
        }
        return Normal::returnCode(Normal::SUC, '删除成功');
    }

    /**
     * 添加参数验证
     * @author: hj
     */
    private static function addArgumentValidate($param)
    {
        if (!isset($param['card_type']) || !in_array($param['card_type'], ['1', '2'])) {
            return Normal::returnCode(Normal::FAIL, '请选择银行卡类型');
        }
        if (!isset($param['bankcard']) || empty($param['bankcard'])) {
            return Normal::returnCode(Normal::FAIL, '请填入银行卡号');
        }
        if (!isset($param['cid']) || empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (!isset($param['bank_id']) || empty($param['bank_id'])) {
            return Normal::returnCode(Normal::FAIL, '请选择开户行');
        }
        if (!isset($param['code']) || empty($param['code'])) {
            return Normal::returnCode(Normal::FAIL, '验证码不能为空');
        }
        if (!isset($param['mobile']) || empty($param['mobile'])) {
            return Normal::returnCode(Normal::FAIL, '手机号码不能为空');
        }
        if (!isset($param['true_name']) || empty($param['true_name'])) {
            return Normal::returnCode(Normal::FAIL, '姓名不能为空');
        }
        if (isset($param['card_type']) && $param['card_type'] == 1) {
            if (!isset($param['idcard']) || empty($param['idcard'])) {
                return Normal::returnCode(Normal::FAIL, '身份证号码不能为空');
            }
        }
        if (isset($param['card_type']) && $param['card_type'] == 2) {
            if (!isset($param['org_name']) || empty($param['org_name'])) {
                return Normal::returnCode(Normal::FAIL, '企业名称不能为空');
            }
            if (!isset($param['org_code']) || empty($param['org_code'])) {
                return Normal::returnCode(Normal::FAIL, '企业代码不能为空');
            }
        }
        return Normal::returnCode(Normal::SUC, '验证通过');
    }
}